#include "stdafx.h"
#include "ZOdbcCommand.h"
#include "ZOdbcConnection.h"
#include "ZOdbcRecordset.h"
#include <assert.h>

namespace	Z	{

namespace	Odbc	{

//------------------------------------------------------------------------------------------------------------------------
Command::Command(Connection& kConnection)
:	mConnection(kConnection)
{
}

Command::~Command()
{
}

RecordsetPtr Command::execute()
{
	if(!mConnection.open())
		return RecordsetPtr();

	RecordsetPtr kRecordsetPtr(new Recordset(mConnection));
	if(execDirect(*kRecordsetPtr))
		return kRecordsetPtr;

	kRecordsetPtr.reset();
	return kRecordsetPtr;
}

bool Command::execDirect(Recordset& kRecordset)
{
	mParameters.bind(kRecordset.stmt());

	SQLRETURN retcode	= ::SQLExecDirect(kRecordset.stmt(), (SQLCHAR*)mCommandText.c_str(), mCommandText.length());
	if(retcode == SQL_NEED_DATA)
		retcode	= mParameters.putData(kRecordset.stmt());

	if(SQL_SUCCEEDED(retcode) || retcode == SQL_NO_DATA_FOUND)	{
		kRecordset.bind();
		return true;
	}

	diagnosis(SQL_HANDLE_STMT, kRecordset.stmt(), mCommandText);
	return false;
}

void Command::setCommandText(const char* format, ...)
{
	va_list args;
	va_start(args, format);
	setCommandText(format, args);
	va_end(args);
}

void Command::setCommandText(const char* format, va_list args)
{
	const size_t kMaxBufSize	= 1024;
	const size_t kMaxChars	= kMaxBufSize - 1;
	char kBuffer[kMaxBufSize];
	int kCharsWritten	= ::_vsnprintf_s(kBuffer, kMaxBufSize, kMaxChars, format, args);
	assert(0 < kCharsWritten);
	mCommandText	= kBuffer;
}

}

}